﻿using OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.IO;
using System.Linq;
using System.Reflection;

namespace Core.Helper
{
    public sealed class Excel
    {
        /// <summary>
        /// 导出Excel。数据为Null则导出模板
        /// </summary>
        /// <typeparam name="T">实体类，用于导出模板</typeparam>
        /// <param name="name">Sheet名称</param>
        /// <param name="source">数据内容</param>
        /// <returns>字节数组</returns>
        public static byte[] Export<T>(string name, IEnumerable<T> source = null) where T : class, new()
        {
            using (ExcelPackage package = new ExcelPackage())
            {
                ExcelWorksheet sheet = package.Workbook.Worksheets.Add(name);
                PropertyInfo[] properties = typeof(T).GetProperties();
                // 第一行写入标题，读取Column的描述
                for (int i = 0; i < properties.Length; i++)
                {
                    var property = properties[i];
                    ColumnAttribute[] columns = property.GetCustomAttributes(typeof(ColumnAttribute), true) as ColumnAttribute[];
                    if (columns == null) { throw new Exception("字段缺少列说明，请在字段上加上Column标签"); }
                    ColumnAttribute column = columns[0];
                    sheet.Cells[1, (i + 1)].Value = column.Name;
                }

                // 没有内容则导出模板
                if (source.IsNotNull())
                {
                    // 写入内容
                    for (int x = 0; x < properties.Length; x++)
                    {
                        var property = properties[x];
                        int row = 2;
                        foreach (var item in source)
                        {
                            sheet.Cells[row, x + 1].Value = item.GetType().GetProperty(property.Name).GetValue(item, null);
                            row++;
                        }
                    }
                }

                return package.GetAsByteArray();
            }
        }

        /// <summary>
        /// Execl导入
        /// </summary>
        /// <typeparam name="T">数据类型</typeparam>
        /// <param name="path">数据源文件地址</param>
        /// <param name="sheet">要指定的页名称</param>
        /// <returns>数据列表</returns>
        public static List<T> Import<T>(string path, string sheet = null) where T : class, new()
        {
            using (ExcelPackage package = new ExcelPackage(new FileInfo(path)))
            {
                ExcelWorkbook workbook = package.Workbook;
                ExcelWorksheet worksheet = sheet.IsNotNullOrEmpty() ? workbook.Worksheets[sheet] : workbook.Worksheets.First();
                if (worksheet.IsNull()) { throw new Exception("没有找到数据源"); }
                return worksheet.ConvertSheetToObjects<T>().ToList();
            }
        }
    }
}